// ignore_for_file: unused_element

import 'package:flutter/material.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:tiktokadult/hj_page/pre_sale/pre_sale_service.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../../alert_business/mine/vip_level_dialog.dart';
import '../../../../hj_model/video_model.dart';
import '../../../../hj_utils/const.dart';
import '../../../../tools_base/global_store/store.dart';
import '../../../../tools_base/video_download/video_download_manager.dart';
import '../../../../tools_base/video_download/video_load_record.dart';
import '../../../video/view/detail_top_right_view.dart';

class VideoLoadButton extends StatefulWidget {
  final VideoModel? videoModel;
  final bool isShort; //false长视频  true 短视频
  final Function? callback;

  const VideoLoadButton({
    Key? key,
    this.videoModel,
    this.isShort = true,
    this.callback,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _VideoLoadButtonState();
  }
}

class _VideoLoadButtonState extends State<VideoLoadButton> {
  DownloadCallBack? _callBack;

  VideoModel? get _videoInfo => widget.videoModel;

  int get allDownCount => globalStore.getWallet()?.downloadCount ?? 0;

  bool get isCartoon => _videoInfo?.videoType == 1;

  int get loadStatus {
    // 0 未下载，1下载中，2下载完成
    if (_videoInfo?.localPath?.isNotEmpty == true || _videoInfo?.isLoaderRunning == "2") {
      return 2;
    } else if (_videoInfo?.isLoaderRunning == "1") {
      return 1;
    } else {
      return 0;
    }
  }

  String get imagePath {
    if (widget.isShort) {
      return "download_short.png".videoPath;
    } else {
      return "download.png".videoPath;
    }
  }

  @override
  void initState() {
    super.initState();
    globalStore.refreshWallet();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _loadData();
    });
  }

  void _loadData() async {
    _callBack = DownloadCallBack(
      success: (url) {
        if (_videoInfo?.realVideoUrl == url) {
          _videoInfo?.isLoaderRunning = "2";
          _videoInfo?.loadProgress = "100.00";
        }
        // showToast( "视频下载完成");
        setState(() {});
      },
      fail: (url, error) {
        if (_videoInfo?.realVideoUrl == url) {
          _videoInfo?.isLoaderRunning = "0";
        }
        showToast("缓存加载失败");
        setState(() {});
      },
      progress: (url, progress) {
        var urlD = _videoInfo?.realVideoUrl;
        if (urlD == url) {
          _videoInfo?.isLoaderRunning = "1";
          _videoInfo?.loadProgress = progress;
          setState(() {});
        }
      },
    );
    dynamic result = await VideoDownloadManager.instance.searchInfo(
      url: _videoInfo?.realVideoUrl,
      callBack: _callBack,
    );
    if (result is Map) {
      Map fileInfoMap = result;
      String? filePath = fileInfoMap["localPath"];
      if (filePath != null && filePath.isNotEmpty == true) {
        _videoInfo?.localPath = filePath;
      } else if (fileInfoMap["isLoaderRunning"] == "1") {
        _videoInfo?.isLoaderRunning = "1";
        _videoInfo?.loadProgress = fileInfoMap["progress"];
      } else {}
      if (mounted) {
        setState(() {});
      }
    }
  }

  Future<bool> _checkPermission() async {
    var status = await Permission.storage.status;
    if (!status.isGranted) {
      status = await Permission.storage.request();
    }
    return status.isGranted;
  }

  void _downEvent() async {
    downloadAction();
    if (presaleProvider.isOpen && presaleProvider.hasLimit == true && (presaleProvider.remain?.todayDownloadCount ?? 0) > 0) {
      final resp = await PreSaleService.consumePrivilege(privilegeType: 'download');
      if (resp.isSuccess) {
        presaleProvider.todayDownloadReduce();
        downloadAction();
      }
    } else {
      if (!globalStore.isVIP()) {
        showVipLevelDialog("您还不是VIP,无法使用下载功能");
        return;
      }
      LongVideStatus status = longVideoStatusDesc(widget.videoModel);
      if (status.isNeedBuy) {
        showToast("您未购买当前视频，无法使用下载功能");
        return;
      }
      if (allDownCount == 0) {
        showToast("今日下载次数已使用完，明日再来");
        return;
      }
      if (loadStatus == 0) {
        final result = await MineService.reduceDownloadCount();
        if (result) {
          globalStore.refreshWallet();
          downloadAction();
        }
      } else if (loadStatus == 1) {
        showToast("正在下载中...");
      } else if (loadStatus == 2) {
        showToast("已下载完成");
      } else {}
    }
    widget.callback?.call();
  }

  downloadAction() async {
    // 下载
    _checkPermission().then((hasGranted) async {
      var result = await VideoDownloadManager.instance.download(
        url: widget.videoModel?.realVideoUrl ?? "",
        callBack: _callBack,
      );
      if (result == null) {
        CacheMediaType movieType = CacheMediaType.video;
        if (widget.videoModel?.videoType == 1) {
          movieType = CacheMediaType.cartoon;
        }
        if (widget.isShort) {
          movieType = CacheMediaType.short;
        }

        VideoLoadRecord.instance.saveVideoInfo(movieType, widget.videoModel);
      }
      if (result == null) {
        _videoInfo?.isLoaderRunning = "1";
        showToast("开始下载...");
      } else if (result == "正在执行") {
        _videoInfo?.isLoaderRunning = "1";
        showToast("正在下载中...");
      } else if (result == "已下载完成了") {
        _videoInfo?.isLoaderRunning = "2";
        showToast("已下载完成");
      } else {
        showToast(result.toString());
      }
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    String statusDesc = "下载";
    if (loadStatus == 1) {
      statusDesc = "下载中";
    }
    if (loadStatus == 2) {
      statusDesc = "已下载";
    }
    return InkWell(
      onTap: _downEvent,
      child: widget.isShort
          ? Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                SizedBox(
                  width: 30,
                  height: 30,
                  child: Image.asset(imagePath),
                ),
                Text(
                  statusDesc,
                  style: TextStyle(
                    color: Color(0xffdcdcdc),
                    fontSize: 12,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            )
          : Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                SizedBox(
                  width: 14,
                  height: 14,
                  child: Image.asset(imagePath),
                ),
                const SizedBox(width: 2),
                Text(
                  statusDesc,
                  style: TextStyle(
                    color: Color(0x8CFFFFFF),
                    fontSize: 12,
                  ),
                ),
              ],
            ),
    );
  }

  @override
  void dispose() {
    VideoDownloadManager.instance.removeAllCallBack();
    super.dispose();
  }
}
